package com.hewang.thread;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ThreadTestActivity extends AppCompatActivity {
    private final String TAG = "hewang-thread";
    private static Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.hewang.helloandroid.R.layout.activity_thread_test);

        HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            // 处理消息这里是主线程
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 1:
                        // 处理消息
                        Log.d(TAG, "收到消息");
                        Toast.makeText(ThreadTestActivity.this, "收到消息", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        Button btn = (Button)findViewById(com.hewang.helloandroid.R.id.btn_start_thread);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 线程里面是不能更新UI的，需要通过发送消息，让处理事件处理
                        handler.sendEmptyMessage(1);
                    }
                });
            }
        });
    }
}